<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-table
    :data="items"
    border
    style="width: 80%"
    max-height="400">
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="date" label="日期"></el-table-column>
        <el-table-column  label="价格">
            <template slot-scope="scope"><p>¥{{scope.row.price}}</p></template>
        </el-table-column>
        <el-table-column label="数量">
            <template slot-scope="scope">
                <span @click="subItem(scope.row)">-</span><input type="text" v-model="scope.row.num" style="width: 20px;margin: 5px 5px"><span @click="addItem(scope.row)">+</span>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
           <template slot-scope="scope">
               <el-button @click="deleteHandler(scope.$index)" type="text" size="small">移除</el-button>
           </template>
        </el-table-column>
    </el-table>
    <div>总价格：<span>¥{{totalPrice}}</span></div>
</div>
</body>
<script>
 var vm  = new Vue({
     el: '#app',
     data: {
         totalPrice: 0,
         items: [
             {"id":1,"name": "《java编程思想》","date": "2020-02-01","price": 98,"num":0},
             {"id":2,"name": "《数据分析与原理》","date": "2020-12-01","price": 39,"num":0},
             {"id":3,"name": "《Hadoop权威指南》","date": "2020-03-12","price": 58,"num":0},
             {"id":4,"name": "《代码大全》","date": "2020-09-20","price": 128,"num":0}
         ]
     },
     methods: {
        addItem(item){
            item.num ++;
            this.calculate()
        },
        subItem(item){
            if (item.num > 0) {
                item.num --
            }else{
                item.num = 0
            }
            this.calculate()
        },
         calculate(){
            this.totalPrice = 0
             this.items.forEach(item => {
                 this.totalPrice += (item.price * item.num)
             })
         },
         deleteHandler(index){
            console.log(index)
            this.items.splice(index,1)
             this.calculate()
         }

     }
 })
</script>
</html>